﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Controls;
using System.Configuration;
using System.Data.Common;
using ESRI.ArcGIS.Geometry;
using pnmodel;
using com.zjgis.control;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;

namespace WindowsApplication1.dialog
{
    public partial class QueryResultPanel : UserControl
    {
        private QueryResultPanel()
        {
            InitializeComponent();
        }
        private static QueryResultPanel instance;
        public static QueryResultPanel Instance
        {
            get
            {
                if (instance == null)
                    instance = new QueryResultPanel();
                return instance;
            }
        }

        private void toolStripStatusLabel1_Click(object sender, EventArgs e)
        {
            this.Visible = false;
        }
        public void SetVisible()
        {
            Visible = true;
        }
        private IMapControl2 map;
        public IMapControl2 MapControl
        {
            set
            {
                map = value;
            }
        }

        public void Clear()
        {
            treeView1.Nodes.Clear();
        }

        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            TreeNode node = e.Node;
            if (node.Nodes.Count == 0 && node.ContextMenuStrip != null)
            {
                System.Drawing.Point p = e.Location;
                p.Offset(this.Location);
                node.ContextMenuStrip.Show(this,p);
                
            }
        }
        private void AddClick2UpdateAttStripItem(ToolStripItem strip, string aliasname,TreeNode node,string tag,IMapControl2 c2, TreeNode tnode){
            strip.Click += delegate
            {
                InputBox box = InputBox.Show("编辑属性 " + aliasname, node.Text.Substring(node.Text.LastIndexOf(':') + 1).TrimStart(' '));
                if (box.DialogResult == DialogResult.OK)
                {
                    string text = box.GetInputText();
                    DbConnection conn1 = Form1.CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
                    conn1.Open();
                    DbCommand comm1 = conn1.CreateCommand();
                    try
                    {
                        comm1.CommandText = "update 用电建筑信息 set " + aliasname + " = :p1 where 建筑统一编码 = '" + tag + "'";
                        DbParameter ter = comm1.CreateParameter();
                        ter.Value = text;
                        ter.ParameterName = "p1";
                        comm1.Parameters.Add(ter);
                        if (comm1.ExecuteNonQuery() > 0)
                        {
                            UpdateNode("select * from 用电建筑信息 where 建筑统一编码 = '" + tag + "'", c2, tnode);
                            MessageBox.Show("更新成功");
                        }
                        else
                        {
                            MessageBox.Show("更新失败!");
                        }
                    }
                    catch (Exception ex) { MessageBox.Show("更新失败,原因：" + ex.Message); }
                    finally
                    {
                        conn1.Close();
                    }
                }
            };
        }
        private void AddHuHao2StripItem(ToolStripItem strip1,string aliasname,string sequence,string tag, TreeNode tnode,IMapControl2 c2)
        {
            strip1.Click += delegate
            {
                InputBox box = InputBox.Show("增加 " + aliasname, "");
                if (box.DialogResult == DialogResult.OK)
                {
                    string text = box.GetInputText();
                    if (text.Trim().Length == 0)
                    {
                        return;
                    }
                    DbConnection conn1 = Form1.CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
                    conn1.Open();
                    DbCommand comm1 = conn1.CreateCommand();
                    try
                    {
                        comm1.CommandText = "delete 建筑编码2电力户号 where 电力户号 = '" + text + "'";
                        comm1.ExecuteNonQuery();
                        comm1.CommandText = "insert into 建筑编码2电力户号 (objectid,建筑统一编码,电力户号) values (" + sequence + ".nextval," + tag + "," + text + ")";

                        if (comm1.ExecuteNonQuery() > 0)
                        {
                            UpdateNode("select * from 用电建筑信息 where 建筑统一编码 = '" + tag + "'", c2, tnode);
                            MessageBox.Show("更新成功");
                        }
                        else
                        {
                            MessageBox.Show("更新失败!");
                        }
                    }
                    catch (Exception ex) { MessageBox.Show("更新失败,原因：" + ex.Message); }
                    finally
                    {
                        conn1.Close();
                    }
                }
            };
        }
        private void EditOrDeleteHuhao2StripItem(ToolStripItem strip,string aliasname,TreeNode node,string value,string tag, TreeNode tnode,IMapControl2 c2)
        {
            strip.Click += delegate
            {
                InputBox box = InputBox.Show("编辑属性 " + aliasname, node.Text.Substring(node.Text.LastIndexOf(':') + 1).TrimStart(' '));
                if (box.DialogResult == DialogResult.OK)
                {
                    string text = box.GetInputText();
                    DbConnection conn1 = Form1.CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
                    conn1.Open();
                    DbCommand comm1 = conn1.CreateCommand();
                    try
                    {
                        if (text.Trim().Length != 0)
                        {
                            comm1.CommandText = "update 建筑编码2电力户号 set " + aliasname + " = :p1 where 电力户号 = '" + value + "'";
                            DbParameter ter = comm1.CreateParameter();
                            ter.Value = text;
                            ter.ParameterName = "p1";
                            comm1.Parameters.Add(ter);
                        }
                        else
                        {
                            comm1.CommandText = "delete from 建筑编码2电力户号 where 电力户号 = '" + node.Text.Substring(node.Text.LastIndexOf(':') + 2) + "'";
                        }
                        if (comm1.ExecuteNonQuery() > 0)
                        {
                            UpdateNode("select * from 用电建筑信息 where 建筑统一编码 = '" + tag + "'", c2, tnode);
                            MessageBox.Show("更新成功");
                        }
                        else
                        {
                            MessageBox.Show("更新失败!");
                        }
                    }
                    catch (Exception ex) { MessageBox.Show("更新失败,原因：" + ex.Message); }
                    finally
                    {
                        conn1.Close();
                    }
                }
            };
        }
        public void ShowQueryResult(string sql, IMapControl2 c2)
        {
            DbConnection conn = Form1.CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
            conn.Open();
            DbCommand command = conn.CreateCommand();
            command.CommandText = "select registration_id from sde.table_registry t where upper(owner) = '" + ((IDataset)Form1.建筑图层.FeatureClass).Workspace.ConnectionProperties.GetProperty("user").ToString().ToUpper() + "' and upper(table_name) = '建筑编码2电力户号'";
            object obj1 = command.ExecuteScalar();
            if (obj1 == null)
            {
                MessageBox.Show(Settings.用电建筑信息 + "objectid 字段序列有误！");
                conn.Close();
                return;
            }
            string sequence = "R" + obj1.ToString();
            DbCommand huhaocommand = conn.CreateCommand();
            command.CommandText = sql;
            DbDataReader reader = command.ExecuteReader();
            string tablename = ConfigurationManager.AppSettings["建筑图层"];
            string idname = ConfigurationManager.AppSettings["用电建筑编号"];
            string fieldname = idname;
            QueryResultPanel form = QueryResultPanel.Instance;
            form.Clear();
            TreeNode root = form.treeView1.Nodes.Add("用电建筑信息");
            int tagindex = reader.GetOrdinal(idname);
            int shapeindex = reader.GetOrdinal("shape");
            int shapetypeindex = reader.GetOrdinal("shapetype");
            while (reader.Read())
            {
                int shapetype = int.Parse(reader.GetValue(shapetypeindex).ToString());
                IGeometry geom1 = PnGeometryUtility.GetGeometry(shapetype + 2000, reader.GetString(shapeindex));
                string tag = reader.GetString(tagindex);
                TreeNode tnode = root.Nodes.Add(tag);
                int fcount = reader.FieldCount;
                
                for (int i = 0; i < fcount - 1; i++)
                {
                    if (i == tagindex || i == shapeindex || i == shapetypeindex)
                    {
                        continue;
                    }
                    string aliasname = reader.GetName(i);
                    string value = reader.GetValue(i).ToString();
                    int length = UnicodeEncoding.Default.GetByteCount(aliasname) - aliasname.Length;
                    TreeNode node = tnode.Nodes.Add(aliasname.PadRight(20 - length, ' ') + " : " + value);
                    ContextMenuStrip cms = new ContextMenuStrip();
                    node.ContextMenuStrip = cms;
                    ToolStripItem strip = cms.Items.Add("编辑");
                    AddClick2UpdateAttStripItem( strip,  aliasname, node, tag, c2,  tnode);
                    ToolStripItem strip1 = cms.Items.Add("增加电力户号");
                    AddHuHao2StripItem(strip1, aliasname, sequence, tag, tnode, c2);
                    
                }
                huhaocommand.CommandText = "select 电力户号 from 建筑编码2电力户号 t where t.建筑统一编码 = '" + tag + "'";
                DbDataReader reader2 = huhaocommand.ExecuteReader();
                while (reader2.Read())
                {
                    string aliasname = reader2.GetName(0);
                    string value = reader2.GetValue(0).ToString();
                    int length = UnicodeEncoding.Default.GetByteCount(aliasname) - aliasname.Length;
                    TreeNode node = tnode.Nodes.Add(aliasname.PadRight(20 - length, ' ') + " : " + value);
                    ContextMenuStrip cms = new ContextMenuStrip();
                    node.ContextMenuStrip = cms;
                    ToolStripItem strip = cms.Items.Add("编辑");
                    EditOrDeleteHuhao2StripItem(strip, aliasname, node, value, tag, tnode, c2);
                    ToolStripItem strip1 = cms.Items.Add("增加电力户号");
                    AddHuHao2StripItem(strip1, aliasname, sequence, tag, tnode, c2);
                    
                }
                reader2.Close();
                ContextMenuStrip cm = new ContextMenuStrip();
                Form1.addContextMenuStrip(geom1, ref cm, c2);
                ToolStripItem item = cm.Items.Add("删除");
                item.Click += delegate
                {
                    DbConnection conn1 = Form1.CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
                    conn1.Open();
                    string sql1 = "delete from 用电建筑信息 where 建筑统一编码 = '" + tag + "'";
                    DbCommand command1 = conn1.CreateCommand();
                    command1.CommandText = sql1;
                    if (command1.ExecuteNonQuery() != 0)
                    {
                        tnode.Remove();
                    }

                    sql1 = "update 建筑 set hasdata = 0 where buildingid = '" + tag + "'";
                    command1.CommandText = sql1;
                    command1.ExecuteNonQuery();
                    sql1 = "update 建筑 set 建筑统一编码 = '' where 建筑统一编码 = '" + tag + "'";
                    command1.CommandText = sql1;
                    command1.ExecuteNonQuery();
                    sql1 = "select a.shape.Get_WKT() as shape  from 用电建筑 a where 建筑统一编码 = '" + tag + "'";
                    command1.CommandText = sql1;
                    object obj = command1.ExecuteScalar();
                    if (obj != null)
                    {
                        string geomstr = obj.ToString();
                        geom1 = PnGeometryUtility.GetGeometry(2003, geomstr);
                    }
                    
                    sql1 = "delete from 用电建筑 where 建筑统一编码 = '" + tag + "'";
                    command1.CommandText = sql1;
                    command1.ExecuteNonQuery();
                    IEnvelope env = geom1.Envelope;
                    env.Expand(env.Width * 0.1, env.Height * 0.1, false);
                    c2.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewBackground, null, env);
                    conn1.Close();
                };
                tnode.ContextMenuStrip = cm;
            }
            reader.Close();
            conn.Close();
        }
        public void UpdateNode(string sql, IMapControl2 c2, TreeNode tnode)
        {
            DbConnection conn = Form1.CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
            conn.Open();
            DbCommand command = conn.CreateCommand();
            command.CommandText = "select registration_id from sde.table_registry t where upper(owner) = '" + ((IDataset)Form1.建筑图层.FeatureClass).Workspace.ConnectionProperties.GetProperty("user").ToString().ToUpper() + "' and upper(table_name) = '建筑编码2电力户号'";
            object obj1 = command.ExecuteScalar();
            if (obj1 == null)
            {
                MessageBox.Show(Settings.用电建筑信息 + "objectid 字段序列有误！");
                conn.Close();
                return;
            }
            string sequence = "R" + obj1.ToString();
            DbCommand huhaocommand = conn.CreateCommand();
            command.CommandText = sql;
            DbDataReader reader = command.ExecuteReader();
            string tablename = ConfigurationManager.AppSettings["建筑图层"];
            string idname = ConfigurationManager.AppSettings["用电建筑编号"];
            string fieldname = idname;
           
            int tagindex = reader.GetOrdinal(idname);
            while (reader.Read())
            {
                tnode.Nodes.Clear();
                string tag = reader.GetString(tagindex);                
                int fcount = reader.FieldCount;

                for (int i = 0; i < fcount - 1; i++)
                {
                    if (i == tagindex)
                    {
                        continue;
                    }
                    string aliasname = reader.GetName(i);
                    string value = reader.GetValue(i).ToString();
                    int length = UnicodeEncoding.Default.GetByteCount(aliasname) - aliasname.Length;
                    TreeNode node = tnode.Nodes.Add(aliasname.PadRight(20 - length, ' ') + " : " + value);
                    ContextMenuStrip cms = new ContextMenuStrip();
                    node.ContextMenuStrip = cms;
                    ToolStripItem strip = cms.Items.Add("编辑");
                    AddClick2UpdateAttStripItem(strip, aliasname, node, tag, c2,tnode);
                    ToolStripItem strip1 = cms.Items.Add("增加电力户号");
                    AddHuHao2StripItem(strip1, aliasname, sequence, tag, tnode, c2);
                }
                huhaocommand.CommandText = "select 电力户号 from 建筑编码2电力户号 t where t.建筑统一编码 = '" + tag + "'";
                DbDataReader reader2 = huhaocommand.ExecuteReader();
                while (reader2.Read())
                {
                    string aliasname = reader2.GetName(0);
                    string value = reader2.GetValue(0).ToString();
                    int length = UnicodeEncoding.Default.GetByteCount(aliasname) - aliasname.Length;
                    TreeNode node = tnode.Nodes.Add(aliasname.PadRight(20 - length, ' ') + " : " + value);
                    ContextMenuStrip cms = new ContextMenuStrip();
                    node.ContextMenuStrip = cms;
                    ToolStripItem strip = cms.Items.Add("编辑");
                    EditOrDeleteHuhao2StripItem(strip, aliasname, node, value, tag, tnode, c2);
                    ToolStripItem strip1 = cms.Items.Add("增加电力户号");
                    AddHuHao2StripItem(strip1, aliasname, sequence, tag, tnode, c2);
                }
                reader2.Close();                
            }
            tnode.Expand();
            reader.Close();
            conn.Close();
        }
        
    }
}
